import React, { Component } from "react";
import { Text, View, DatePickerIOS } from "react-native";
import _ from 'lodash';
import { formStore } from "../..";
import styles from './styles';


export default class Options extends Component {
  constructor(props) {
    super(props)
    this.state = {
      value: props.value || '',
      status: 0,
    }
  }
  componentWillReceiveProps(next) {
    this.setState({
      value: next.value,
      options: next.options
    })
  }

  onChange = value => {
    this.setState({ value });
  };
  onCancel = () => {
    if (_.isFunction(this.props.onCancel)) {
      this.props.onCancel();
    } else {
      formStore.dismissDateIOS();
    }
  }
  onOk = () => {
    if (_.isFunction(this.props.onOk)) {
      this.props.onOk(this.state.value);
    } else {
      if (this.state.value) {
        let value;
        if(_.isString(this.state.value)){
          value = this.state.value
        } else {
          let defaultFormat = 'YYYY-MM-DD';
          switch(this.props.mode){
            case 'datetime':
            case 'dateTime':
              defaultFormat = 'YYYY-MM-DD HH:mm:ss';
              break;
            case 'time':
              defaultFormat = 'HH:mm:ss';
              break;
          }
          value = this.state.value.format(this.props.format || defaultFormat)
        }
        formStore.setValue(this.props.fieldKey, value)
      }
      formStore.dismissDateIOS();
    }
  }
  render() {
    return (
      <View style={styles.optionsWrap}>
        <View style={styles.optionHead}>
          <Text style={styles.headbtn} onPress={this.onCancel}>取消</Text>
          <Text style={styles.headbtn} onPress={this.onOk}>确定</Text>
        </View>
        <DatePickerIOS
          date={this.state.value && new Date(this.state.value) || new Date()}
          mode={this.props.mode && this.props.mode.toLowerCase() || 'date'}
          onDateChange={this.onChange}
          style={styles.optionList}
          maximumDate={this.props.maxDate && new Date(this.props.maxDate)}
          minimumDate={this.props.minDate && new Date(this.props.minDate)}
          timeZoneOffsetInMinutes={8 * 60}
        />
      </View>
    );
  }
}